﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Eksponent.RazorRocks.Helpers
{
    public struct MultiKey : IEnumerable
    {
        private readonly object[] _keys;

        public MultiKey(IEnumerable<object> keys)
            : this(keys.ToArray())
        {
        }

        public MultiKey(params object[] keys)
        {
            _keys = keys ?? new object[0];
        }

        public int Length
        {
            get { return _keys.Length; }
        }

        public object this[int index]
        {
            get { return _keys[index]; }
        }

        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            return _keys.GetEnumerator();
        }

        #endregion

        public override int GetHashCode()
        {
            if( _keys.Length == 0 )
            {
                return 1337;
            }
            
            int hash = _keys[0].GetHashCode();
            for (int i = 1, n = _keys.Length; i < n; i++)
            {
                hash ^= _keys[i].GetHashCode();
            }
            return hash;
        }

        public override string ToString()
        {
            return string.Join(", ", _keys);
        }

        public override bool Equals(object obj)
        {
            if (obj is MultiKey)
            {
                var other = (MultiKey) obj;
                if (other._keys.Length == _keys.Length)
                {
                    return _keys.SequenceEqual(other._keys);
                }
            }

            return base.Equals(obj);
        }
    }
}